package com.zhiyan.say.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.util.StringUtils;
import com.zhiyan.common.util.model.Page;
import com.zhiyan.say.dao.ArtworkDao;
import com.zhiyan.say.domain.entity.Artwork;

@Service
@Transactional
public class ArtworkServiceImpl implements ArtworkService {
	@Autowired 
	private ArtworkDao artworkDao;
	
	@Override
	public void add(Artwork artwork){
		try {
			String id = "art" + UUID.randomUUID().toString().replace("-", "");
			artwork.setId(id);
			artworkDao.add(artwork);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public void update(Artwork artwork) {
		try {
			artworkDao.update(artwork);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		
	}

	@Override
	public List<Artwork> query(Map<String, Object> map) {
		try {
			List<Artwork> list = artworkDao.query(map);
			return list;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	@Override
	public Artwork getById(String id){
		try {
			List<String> idList = new ArrayList<String>();
			if (!StringUtils.isEmpty(id)) idList.add(id);
			List<Artwork> list = this.getByIdList(idList);
			
			if (list!=null && list.size()>0) {
				return list.get(0);
			}else{
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public List<Artwork> getByIdList(List<String> idList){
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", idList);
			map.put("status", "1");
			List<Artwork> list = artworkDao.query(map);
			return list;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public List<Artwork> queryPage(Page page, Map<String, Object> map) {
		try {
			List<Artwork> list = artworkDao.query(map);
			int total = list.size();
			page.setTotal(total);
			
			int pageNo = page.getPageNo();
			int pageSize = page.getPageSize();
			int start = (pageNo-1)*pageSize;
			int pageTotal = total%pageSize==0?total/pageSize:total/pageSize+1;
			page.setPageTotal(pageTotal);
			
			map.put("start", start);
			map.put("size", pageSize);
			list = artworkDao.query(map);
			return list;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	@Override
	public void reStatus(String status, List<String> idList) {
		try {
			artworkDao.reStatus(status, idList);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}


}
